<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="90px" inline :rules="rules">
      <el-row>
        <el-form-item label="月份" prop="yearMonth">
          <el-date-picker v-model="form.yearMonth" value-format="yyyy-MM" type="month" placeholder="选择月" clearable />
        </el-form-item>
        <el-form-item label="售电公司" prop="company">
          <el-select v-model="form.company" size="medium" placeholder="请选择售电公司" style="width:200px" filterable clearable @change="changeHandler">
            <el-option v-for="item in companyOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户" prop="accountNoListStr">
          <el-select v-model="form.accountNoListStr" size="medium" placeholder="请选择用户" style="width:200px" clearable filterable>
            <el-option v-for="item in userCompanyOptions" :key="item.id" :label="item.name + item.accountNo" :value="item.accountNo" />
          </el-select>
        </el-form-item>
        <el-button type="primary" size="medium" @click="onSubmit">查询单个用户</el-button>
        <el-button :loading="listSumLoading" type="primary" size="medium" @click="onSubmitSum">查询所有用户</el-button>
        <el-button :loading="exportLoading" type="warning" size="medium" @click="onExport">数据导出</el-button>
      </el-row>
      <el-row v-show="dayElePqTotal !== 0" class="tag-list">
        <el-tag type="info">
          <ul>
            <el-row type="flex" justify="space-between">
              <li>尖用电：<span class="ele-quantity">{{ thisTPqTotal }}</span><span v-html="'&nbsp;&nbsp;千瓦时'" /></li>
              <li>峰用电：<span class="ele-quantity">{{ thisPPqTotal }}</span><span v-html="'&nbsp;&nbsp;千瓦时'" /></li>
              <li>平用电：<span class="ele-quantity">{{ thisNPqTotal }}</span><span v-html="'&nbsp;&nbsp;千瓦时'" /></li>
              <li>谷用电：<span class="ele-quantity">{{ thisVPqTotal }}</span><span v-html="'&nbsp;&nbsp;千瓦时'" /></li>
            </el-row>
            <el-row type="flex" justify="space-between">
              <li>月累计总用电：<span class="ele-quantity">{{ dayElePqTotal }}</span><span v-html="'&nbsp;&nbsp;千瓦时'" /></li>
              <li>预计本月用电：<span class="ele-quantity">{{ dayElePqNextTotal }}</span><span v-html="'&nbsp;&nbsp;千瓦时'" /></li>
            </el-row>
          </ul>
        </el-tag>
      </el-row>
    </el-form>
    <hr>
    <div ref="chartMap0" class="rank-map" />
    <hr>
    <div class="col-map" style="display: flex;justify-content: center;">
      <div ref="chartMap1" class="rank-map" />
      <div ref="chartMap2" class="rank-map" />
    </div>
  </div>
</template>

<script>
import { queryElecData, exportElecData, getUserCompanyOptions } from '@/api/electricity'
import * as echarts from 'echarts'
import { companyOptions } from '@/enum/index'
import { downLoadFile } from '@/utils/download'
import { BigNumber } from 'bignumber.js'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      listLoading: false,
      listSumLoading: false,
      exportLoading: false,
      form: {
        yearMonth: '',
        accountNoListStr: ''
      },
      queryMonth: '',
      rules: {
        yearMonth: [{ required: true, trigger: 'change', message: '请选择月份' }],
        company: [{ required: true, trigger: 'change', message: '请选择售电公司' }],
        accountNoListStr: [{ required: true, trigger: 'change', message: '请选择用户' }]
      },
      userCompanyOptions: [],
      userCompanyOptions_1: [],
      userCompanyOptions_2: [],
      companyOptions,
      // 折线图配置
      option0: {
        title: {
          text: '日电量趋势（千瓦时）'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['尖用电', '峰用电', '平用电', '谷用电', '总用电']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            interval: 0,
            rotate: 45 // 设置标签倾斜角度，单位为度
          },
          data: [
            // '2023-06-01', '2023-06-02', '2023-06-03', '2023-06-04', '2023-06-05', '2023-06-06',
            // '2023-06-07', '2023-06-08', '2023-06-09', '2023-06-10', '2023-0611', '2023-06-12',
            // '2023-06-13', '2023-06-14', '2023-06-15', '2023-06-16', '2023-06-17', '2023-06-18',
            // '2023-06-19', '2023-06-20', '2023-06-21', '2023-06-22', '2023-06-23', '2023-06-24',
            // '2023-06-25', '2023-06-26', '2023-06-27', '2023-06-28', '2023-06-29', '2023-06-30'
          ]
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '尖用电',
            id: 'thisTPq',
            type: 'line',
            data: [
              // 120, 132, 101, 134, 90, 230, 210, 120, 132, 120, 132, 101, 134, 90, 230, 210, 120, 132, 120, 132, 101, 134, 90, 230, 210, 120, 132, 120, 132, 101, 134, 90, 230
            ]
          },
          {
            name: '峰用电',
            id: 'thisPPq',
            type: 'line',
            data: [
              // 220, 182, 191, 234, 290, 330, 310, 220, 182, 220, 182, 191, 234, 290, 330, 310, 220, 182, 220, 182, 191, 234, 290, 330, 310, 220, 182, 220, 182, 191, 234, 290, 330
            ]
          },
          {
            name: '平用电',
            id: 'thisNPq',
            type: 'line',
            data: [
              // 160, 232, 201, 154, 190, 330, 410, 150, 232, 160, 232, 201, 154, 190, 330, 410, 150, 232, 160, 232, 201, 154, 190, 330, 410, 150, 232, 160, 232, 201, 154, 190, 330
            ]
          },
          {
            name: '谷用电',
            id: 'thisVPq',
            type: 'line',
            data: [
              // 160, 132, 101, 134, 90, 230, 210, 120, 132, 160, 132, 101, 134, 90, 230, 210, 120, 132, 160, 132, 101, 134, 90, 230, 210, 120, 132, 160, 132, 101, 134, 90, 230
            ]
          },
          {
            name: '总用电',
            id: 'dayElePq',
            type: 'line',
            data: [
              // 260, 182, 191, 234, 290, 330, 310, 220, 182, 260, 182, 191, 234, 290, 330, 310, 220, 182, 260, 182, 191, 234, 290, 330, 310, 220, 182, 260, 182, 191, 234, 290, 330
            ]
          }
        ]
      },
      option1: {
        title: {
          text: '用电情况',
          subtext: '千瓦时',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            let res = ''
            res += params.marker +
              params.name + '&nbsp;&nbsp;' +
              params.value + '<br>' +
              params.percent.toFixed(1) + '%'
            return res
          }
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '用电情况',
            type: 'pie',
            radius: '50%',
            data: [
              // { value: 1048, name: '尖用电' },
              // { value: 735, name: '峰用电' },
              // { value: 580, name: '平用电' },
              // { value: 484, name: '谷用电' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ],
        label: {
          // echarts饼图内部显示百分比设置
          show: true,
          position: 'inside', // outside 外部显示  inside 内部显示
          formatter: (params) => {
            let res = ''
            res += params.name + ':' + params.percent.toFixed(1) + '%'
            return res
          },
          fontSize: 12 // 字体大小
        }
      },
      option2: {
        title: {
          text: '用电情况',
          subtext: '千瓦时',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['尖用电', '峰用电', '平用电', '谷用电']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [
              // { value: 1048, itemStyle: { color: '#5470c6' }},
              // { value: 735, itemStyle: { color: '#91cc75' }},
              // { value: 580, itemStyle: { color: '#ffdc60' }},
              // { value: 484, itemStyle: { color: '#ee6765' }}
            ],
            type: 'bar'
          }
        ],
        label: {
          show: true,
          position: 'top'
        }
      },
      chartMap0: null,
      chartMap1: null,
      chartMap2: null,
      pqMap: {
        thisTPq: '尖用电',
        thisPPq: '峰用电',
        thisNPq: '平用电',
        thisVPq: '谷用电',
        dayElePq: '总用电'
      },
      thisTPqTotal: 0,
      thisPPqTotal: 0,
      thisNPqTotal: 0,
      thisVPqTotal: 0,
      dayElePqTotal: 0,
      dayElePqNextTotal: 0,
      actDates: 0 // 本月有数据的天数
    }
  },
  created() {
    getUserCompanyOptions().then(res => {
      res.forEach(item => {
        if (item.companyType === 1) {
          this.userCompanyOptions_1.push(item)
        } else if (item.companyType === 2) {
          this.userCompanyOptions_2.push(item)
        }
      })
    }).catch(e => {})
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.listLoading = true
          this.handleReset()
          queryElecData(this.form).then(response => {
            this.list = response
            this.handleData(this.list)
            this.renderData()
            this.handleTotal()
            this.listLoading = false
          }).catch(() => {
            this.listLoading = false
          })
        }
      })
    },
    onSubmitSum() {
      this.handleReset()
      const { yearMonth, company } = this.form
      if (yearMonth && company) {
        this.listSumLoading = true
        queryElecData({ yearMonth }).then(response => {
          this.list = response.filter(item => item.companyType === company)
          this.handleSumData(this.list)
          this.renderData()
          this.handleTotal()
          this.listSumLoading = false
        }).catch(() => {
          this.listSumLoading = false
        })
      } else {
        this.$message.warning('请选择月份和售电公司')
      }
    },
    onExport() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.exportLoading = true
          const { yearMonth } = this.form
          const params = {
            yearMonth
          }
          downLoadFile(exportElecData(), 'xlsx', params, 'get', () => {
            this.$message({ message: '导出成功', type: 'success' })
            this.exportLoading = false
          })
        }
      })
    },
    handleData(data) {
      const arr = this.form.yearMonth.split('-')
      this.queryMonth = parseInt(arr[1])
      const days = new Date(arr[0], arr[1], 0).getDate()

      const dates = []
      for (let i = 1; i <= days; i++) {
        const xLabel = arr[1] + '-' + (i.toString().length === 1 ? '0' : '') + i
        dates.push(xLabel)
      }
      const dataDates = data.map(item => item.day.slice(5)) // 实际数据的天数
      this.option0.xAxis.data = dates // 横坐标，当月所有天数
      const seriesData = {
        thisNPq: [],
        thisVPq: [],
        thisPPq: [],
        dayElePq: [],
        thisTPq: []
      }
      // 用于计算本月预计电量
      this.actDates = 0
      data.forEach((item, index) => {
        this.actDates++
        seriesData.thisNPq.push(item.thisNPq)
        seriesData.thisVPq.push(item.thisVPq)
        seriesData.thisPPq.push(item.thisPPq)
        seriesData.dayElePq.push(item.dayElePq)
        seriesData.thisTPq.push(item.thisTPq)
      })
      // 处理不足整月的数据，用null补齐前面没有的数据
      for (let i = 0; i < dates.length; i++) {
        if (dates[i] !== dataDates[0]) {
          seriesData.thisNPq.unshift(null)
          seriesData.thisVPq.unshift(null)
          seriesData.thisPPq.unshift(null)
          seriesData.dayElePq.unshift(null)
          seriesData.thisTPq.unshift(null)
        } else {
          break
        }
      }
      this.option0.series.forEach(item => {
        item.data = seriesData[item.id]
      })
    },
    handleSumData(data) {
      const arr = this.form.yearMonth.split('-')
      const days = new Date(arr[0], arr[1], 0).getDate()

      const dates = []
      for (let i = 1; i <= days; i++) {
        const xLabel = arr[1] + '-' + (i.toString().length === 1 ? '0' : '') + i
        dates.push(xLabel)
      }
      const dataDates = data.map(item => item.day.slice(5)) // 实际数据的天数
      this.option0.xAxis.data = dates // 横坐标，当月所有天数

      const seriesData = {
        thisNPq: [],
        thisVPq: [],
        thisPPq: [],
        dayElePq: [],
        thisTPq: []
      }
      const accountNoList = {}

      data.forEach(item => {
        if (!accountNoList[item.day]) {
          if (!accountNoList[item.day]) {
            accountNoList[item.day] = []
          }
        }
        accountNoList[item.day].push(item)
      })
      // 用于计算本月预计电量
      this.actDates = 0
      for (const key in accountNoList) {
        this.actDates++
        for (const _key in this.pqMap) {
          const tmp = accountNoList[key].map(item => {
            return item[_key]
          })
          seriesData[_key].push(tmp.reduce((a, c) => {
            return new BigNumber(c).plus(a).valueOf()
          }))
        }
      }
      // 处理不足整月的数据，用null补齐前面没有的数据
      for (let i = 0; i < dates.length; i++) {
        if (dates[i] !== dataDates[0]) {
          seriesData.thisNPq.unshift(null)
          seriesData.thisVPq.unshift(null)
          seriesData.thisPPq.unshift(null)
          seriesData.dayElePq.unshift(null)
          seriesData.thisTPq.unshift(null)
        } else {
          break
        }
      }
      this.option0.series.forEach(item => {
        item.data = seriesData[item.id]
      })
    },
    renderData() {
      if (!this.chartMap0) {
        this.chartMap0 = echarts.init(this.$refs['chartMap0'])
        // 点击折线图上的点
        this.chartMap0.on('click', (params) => {
          // 渲染饼图
          // dataIndex横坐标数组索引， componentIndex纵坐标数组索引，name是横坐标
          const { dataIndex, name } = params
          const pqTmp = {
            thisTPq: 0,
            thisPPq: 0,
            thisNPq: 0,
            thisVPq: 0
          }
          for (let i = 0; i < this.option0.series.length; i++) {
            const item = this.option0.series[i]
            pqTmp[item.id] = this.option0.series[i].data[dataIndex]
          }

          const { thisTPq, thisPPq, thisNPq, thisVPq } = pqTmp
          this.option1.series[0].data = [
            { name: '尖用电', value: thisTPq, itemStyle: { color: '#5470c6' }},
            { name: '峰用电', value: thisPPq, itemStyle: { color: '#91cc75' }},
            { name: '平用电', value: thisNPq, itemStyle: { color: '#ffdc60' }},
            { name: '谷用电', value: thisVPq, itemStyle: { color: '#ee6765' }}
          ]
          this.option1.title.text = name + ' 用电情况饼状图'
          if (!this.chartMap1) {
            this.chartMap1 = echarts.init(this.$refs['chartMap1'])
          }
          this.chartMap1.setOption(this.option1, true)
          // 渲染柱图
          this.option2.series[0].data = [
            { value: thisTPq, itemStyle: { color: '#5470c6' }},
            { value: thisPPq, itemStyle: { color: '#91cc75' }},
            { value: thisNPq, itemStyle: { color: '#ffdc60' }},
            { value: thisVPq, itemStyle: { color: '#ee6765' }}
          ]
          this.option2.title.text = name + ' 用电情况柱状图'
          if (!this.chartMap2) {
            this.chartMap2 = echarts.init(this.$refs['chartMap2'])
          }
          this.chartMap2.setOption(this.option2, true)
        })
      }
      this.chartMap0.setOption(this.option0, true)
    },
    handleTotal() {
      if (this.list.length !== 0) {
        for (const key in this.pqMap) {
          this[key + 'Total'] = this.list.map(item => {
            if (parseFloat(item[key])) {
              return parseFloat(item[key])
            } else {
              return 0
            }
          }).reduce((a, c) => {
            return new BigNumber(c).plus(a).valueOf()
          })
        }
        const date = new Date()
        const dates = this.actDates
        const year = date.getFullYear()
        const month = this.queryMonth
        const days = new Date(year, month, 0).getDate()
        debugger
        this.dayElePqNextTotal = new BigNumber(this.dayElePqTotal).div(dates).times(days).toFixed(0)
      } else {
        this.thisTPqTotal = 0
        this.thisPPqTotal = 0
        this.thisNPqTotal = 0
        this.thisVPqTotal = 0
        this.dayElePqTotal = 0
        this.dayElePqNextTotal = 0
      }
    },
    handleReset() {
      if (this.chartMap1) this.chartMap1.clear()
      if (this.chartMap2) this.chartMap2.clear()
    },
    changeHandler(val) {
      this.form.accountNoListStr = ''
      this.userCompanyOptions = this['userCompanyOptions' + '_' + val]
    }
  }
}
</script>
<style lang="scss">
.el-form-item {
  margin-bottom: 10px;
}
.col-map {
  margin: 30px 0;
  .rank-map{
    height: 600px;
    width: 50%;
  }
  .rank-map + .rank-map {
    border-left: 1px solid #ddd;
  }
}
.rank-map{
  height: 600px;
}
hr{
  border-top: 1px solid #ddd;
  border-bottom: 0;
  margin: 30px 0;
}
.tag-list {
  margin-top: 20px;
  .el-tag {
    height: initial!important;;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    width: 100%;
    .ele-quantity {
      font-weight: 600;
      color: tomato;
    }
    ul{
      padding: 0;
      width: 80%;
      .el-row {
        li {
          list-style-type: none;
          line-height: 20px;
          width: 25%;
          display: inline-block;
        }
      }
      .el-row+.el-row {
        margin-top: 20px;
      }
    }
  }
}

</style>
